package com.xuyy.exportword.util;


import com.xuyy.exportword.bean.FileParams;
import com.xuyy.exportword.exception.MyTemplateExceptionHandler;
import freemarker.cache.MruCacheStorage;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 生成word 工具类
 *
 * @author 14258
 */
public class WordUtil {
    private Configuration configuration = null;

    public WordUtil() {
        configuration = new Configuration(Configuration.VERSION_2_3_27);
        configuration.setTemplateExceptionHandler(new MyTemplateExceptionHandler());
        configuration.setDefaultEncoding("utf-8");

    }

    /**
     * @param response
     * @param fileParams 输入输出文件夹和文件名
     * @param dataMap    填充word占位符数据
     */
    public void createWord(HttpServletResponse response, FileParams fileParams, Map<String, Object> dataMap) {
        //设置模板装置方法和路径，FreeMarker支持多种模板装载方法。可以重servlet，classpath,数据库装载。
        //加载模板文件，放在/doc下
        configuration.setClassForTemplateLoading(this.getClass(), fileParams.getSourceFilePath()); // FTL文件所存在的位置，必须写明路径
        OutputStreamWriter output = null;
        try {
            // 定义Template对象，注意模板类型名字与templetName要一致
            Template template = configuration.getTemplate(fileParams.getSourceTemplateName());
            output = new OutputStreamWriter(response.getOutputStream());
            // 指明这是一个下载的respond
            response.reset();
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition","attachment; filename=" + fileParams.getOutTemplateName());
            // 合并模板和数据模型
            template.process(dataMap, output);
            // 手动清空模板缓存
            // configuration.clearTemplateCache();
            configuration.setCacheStorage(new MruCacheStorage(20, 250));
        } catch (IOException e) {

            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        } finally {
            try {
                output.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public String saveFile() {
        String nowpath = System.getProperty("user.dir");
        String path = nowpath.replace("bin", "webapps");
        path += "\\" + "TestWeb" + "\\" + "word";
        File tmp = new File(path);
        if (!tmp.exists()) {
            tmp.mkdirs();
        }
        return path;
    }
}
